package cn.xunjie.ymcc.mq.consumer;

import cn.xunjie.ymcc.domain.PayOrder;
import cn.xunjie.ymcc.dto.PayDto;
import cn.xunjie.ymcc.service.IPayOrderService;
import cn.xunjie.ymcc.util.AssertUtil;
import com.alibaba.fastjson.JSONObject;
import org.apache.rocketmq.common.message.MessageExt;
import org.apache.rocketmq.spring.annotation.RocketMQMessageListener;
import org.apache.rocketmq.spring.core.RocketMQListener;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.util.Date;

/**
 *
 * 课程订单生成支付订单的消费者
 * 消费者只能使用集群模式（要被多个消费就使用广播模式）（messagemodel）
 */
@Component
@RocketMQMessageListener(
        consumerGroup = "course-order-pay-consumer",
        topic = "course-order-topic",
        selectorExpression = "course-order-tag"
)
public class courseOrder2PayOrderConsumer implements RocketMQListener<MessageExt> {
    @Autowired
    private IPayOrderService payOrderService;
    /**
     * 保存支付单
     * @param messageExt
     */
    @Override
    public void onMessage(MessageExt messageExt) {
        synchronized ( messageExt.getBody()){
            byte[] body = messageExt.getBody();
            AssertUtil.isNotNull(body,"消息体为空");
            //数组不能直接jsontostring

            String jsonStr = new String(body, StandardCharsets.UTF_8);
            PayDto payDto = JSONObject.parseObject(jsonStr, PayDto.class);
            PayOrder payOrder =  payOrderService.selectOrderNo(payDto.getOrderNo());
            if(payOrder != null){
                return;//不报错表示签收
            }
            payOrder = new PayOrder();
            BeanUtils.copyProperties(payDto,payOrder);
            payOrder.setCreateTime(new Date());
            payOrder.setPayStatus(PayOrder.STAE_WAIT_PAY);
            payOrderService.insert(payOrder);

        }

    }
}
